package web;

import helperclasses.Furnizori;
import helperclasses.MyDataColector;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.ModifyFurnizori;

/**
 * Servlet implementation class ViewSupplier
 */
public class ViewSupplier extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ViewSupplier() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("m").equals("add")) {
			if (request.getParameter("id") != null) {
				MyDataColector dc = new MyDataColector();
				List<Furnizori> furn = new ArrayList<Furnizori>();
				furn = dc.getFurnizor(Integer.parseInt(request.getParameter("id")));
				request.setAttribute("furn", furn.get(0));
				RequestDispatcher view = request.getRequestDispatcher("adaugarefurnizor.jsp");
				view.forward(request, response);
			} else {
				RequestDispatcher view = request.getRequestDispatcher("adaugarefurnizor.jsp");
				view.forward(request, response);
			}
		} else if (request.getParameter("m").equals("view")) {
			MyDataColector dc = new MyDataColector();
			request.setAttribute("furnizoriList", dc.getFurnizor(-1));
			RequestDispatcher view = request.getRequestDispatcher("vizualizarefurnizor.jsp");
			view.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Furnizori furn = new Furnizori();
		ModifyFurnizori mfurn = new ModifyFurnizori();

		furn.setFurnizorName(request.getParameter("nume"));
		furn.setFurnizorAddress(request.getParameter("adresa"));
		furn.setFurnizorTelephone(request.getParameter("telefon"));
		try {
			System.out.println(request.getParameter("id"));
			if (request.getParameter("id").isEmpty()) {
				mfurn.SaveFurnizori(furn);
			} else {
				furn.setFurnizorId(Integer.parseInt(request.getParameter("id")));
				mfurn.EditFurnizori(furn);
			}
		} catch (SQLException e) {

			e.printStackTrace();
		}

		response.sendRedirect(response.encodeRedirectURL("suppliers.do?m=view"));

	}

}
